import { isNumber } from '@/utils/is';
import { computed, Ref, unref } from 'vue';
import { ColProps } from 'ant-design-vue';
import type { FormProps, FormSchema } from '../types/form';

export function useItemLabelWidth(schemaItemRef: Ref<FormSchema>, propsRef: Ref<FormProps>) {
	return computed(() => {
		const schemaItem = unref(schemaItemRef);
		const { labelCol = {} as object, wrapperCol = {} } = schemaItem.itemProps || {};
		const { labelWidth, invalidGlobalLabelWidth } = schemaItem;

		const { labelWidth: globalLabelWidth, labelCol: globalLabelCol, wrapperCol: globWrapperCol } = unref(propsRef);

		// If labelWidth is set globally, all items setting
		if ((!globalLabelWidth && !labelWidth && !globalLabelCol) || invalidGlobalLabelWidth) {
			(labelCol as any).style = {
				textAlign: 'left',
				width: 'auto',
			};
			return { labelCol, wrapperCol };
		}

		let width = labelWidth || globalLabelWidth;
		if (width) {
			width = isNumber(width) ? `${width}px` : width;
		}

		const col = { ...(globalLabelCol as ColProps), ...(labelCol as ColProps) } as ColProps;
		const wrapCol = { ...(globWrapperCol as ColProps), ...(wrapperCol as ColProps) };

		return {
			labelCol: { style: { width }, ...col },
			wrapperCol: { style: { width: `calc(100% - ${width})` }, ...wrapCol },
		};
	});
}
